<template>
  <a-button
    style="margin-bottom: 5px"
    type="primary"
    size="small"
    @click="addTable()"
  >
    添加字段
  </a-button>
  <a-table
    :data-source="dataList"
    :columns="columns"
    :pagination="pagination"
    rowKey="syncTableId"
  >
    <template #status="{ text }">
      {{ text == "1" ? "启用" : "停用" }}
    </template>
    <template #action="{ record }">
      <a-popconfirm
        title="确定要删除吗?"
        @confirm="onDelete(record)"
        okText="确定"
        cancelText="取消"
      >
        <a>删除</a>
      </a-popconfirm>
      <a-divider type="vertical" />
      <a @click="onEdit(record)">修改</a>
      <a-divider type="vertical" />
      <a @click="onUpdateStatus(record, 0)" v-if="record.status == 1">禁用</a>
      <a @click="onUpdateStatus(record, 1)" v-else>启用</a>
    </template>
  </a-table>
  <a-modal
    v-model:visible="visible"
    v-model:title="modelTitle"
    @ok="handleOk"
    width="70%"
    okText="保存"
    cancelText="取消"
    :centered="true"
  >
    <a-form :model="formState">
      <a-row>
        <a-col :span="12">
          <a-form-item label="说明">
            <a-input v-model:value="formState.name" />
          </a-form-item>
        </a-col>
        <a-col :span="12" class="paddLeft">
          <a-form-item label="中心库表名">
            <a-select
              v-model:value="formState.cenTableName"
              :options="optionsCenterTable"
            >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span="12">
          <a-form-item label="临时库表名">
            <a-select
              v-model:value="formState.tmpTableName"
              :options="optionsTempTable"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12" class="paddLeft">
          <a-form-item label="分页大小">
            <a-input v-model:value="formState.pageSize" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="接口地址">
        <a-input v-model:value="formState.apiUrl" />
      </a-form-item>
      <a-button
        style="margin-bottom: 5px"
        type="primary"
        size="small"
        @click="addField()"
      >
        添加字段
      </a-button>
      <a-table
        :data-source="formState.fields"
        :columns="columnsFormState"
        rowKey="apiFieldName"
      >
        <template
          v-for="col in [
            'apiFieldName',
            'cenFieldName',
            'tmpFieldName',
            'opType',
            'defaultVal',
          ]"
          #[col]="{ text, record }"
          :key="col"
        >
          <div>
            <template v-if="editableData[record.apiFieldName]">
              <a-input
                v-if="col == 'apiFieldName' || col == 'defaultVal'"
                v-model:value="editableData[record.apiFieldName][col]"
                style="margin: -5px 0"
              />
              <a-select
                v-else-if="col === 'cenFieldName'"
                v-model:value="editableData[record.apiFieldName][col]"
                style="width: 120px"
                :options="optionsCenter"
              >
              </a-select>
              <a-select
                v-else-if="col === 'tmpFieldName'"
                v-model:value="editableData[record.apiFieldName][col]"
                style="width: 120px"
                :options="optionsTemp"
              >
              </a-select>
              <a-select
                v-else-if="col === 'opType'"
                v-model:value="editableData[record.apiFieldName][col]"
                style="width: 120px"
              >
                <a-select-option value="1">主键</a-select-option>
                <a-select-option value="2">保存</a-select-option>
                <a-select-option value="3">回写</a-select-option>
              </a-select>
            </template>
            <template v-else>
              <template v-if="col === 'opType'">
                {{
                  text == "1"
                    ? "主键"
                    : text == "2"
                    ? "保存"
                    : text == "3"
                    ? "回写"
                    : "--"
                }}
              </template>
              <template v-else>
                {{ text }}
              </template>
            </template>
          </div>
        </template>
        <template #operation="{ record }">
          <div class="editable-row-operations">
            <span v-if="editableData[record.apiFieldName]">
              <a @click="save(record.apiFieldName)">保存</a>
              <a-divider type="vertical" />
              <a @click="cancel(record.apiFieldName)">取消</a>
            </span>
            <span v-else>
              <a @click="edit(record)">修改</a>
              <a-divider type="vertical" />
              <a @click="remove(record.apiFieldName)">删除</a>
            </span>
          </div>
        </template>
      </a-table>
    </a-form>
  </a-modal>
</template>
<script>
import { cloneDeep } from "lodash-es";
import { reactive, ref, toRefs, onBeforeMount } from "vue";

import { 
    ApiMachList,
    ApiMachDelete,
    ApiMachGetDetail,
    ApiMachUpdateStatus,
    ApiMachGetSourceTable,
    ApiMachGetTargetTable,
    ApiMachSaveSyncConfig,
    ApiMachGetTargetField,
    ApiMachGetSourceField
   } from "@/api/api";
import { message } from "ant-design-vue";
// import EditManage from "@/components/EditManage";
export default {
  components: {},

  setup() {
    const editableData = reactive({});

    const state = reactive({
      spinning: false,
      visible: false,
      modelTitle: "修改",
      dataList: [],
      formState: {
        apiUrl: "http://localhost:9002/Test/SyncData",
        cenTableName: "中心库表名",
        fields: [
          {
            apiFieldName: "接口字段名",
            cenFieldName: "中心库字段名",
            opType: 1,
            tmpFieldName: "临时库字段名",
          },
        ],
        name: "说明",
        pageSize: "0",
        tmpTableName: "临时库表名",
      },
      pagination: {
        showQuickJumper: true,
        pageSize: 5,
        showTotal: (total) => `共 ${total} 条数据`,
        showSizeChanger: true,
        pageSizeOptions: ["10", "15", "30", "40", "50"],
      },
      searchText: "",
      searchedColumn: "",
      optionsCenterTable: [], //中心库表列表
      optionsTempTable: [], //临时库表列表
      optionsCenter: [],
      optionsTemp: [],
    });

    const searchInput = ref();
    const columnsFormState = [
      {
        title: "接口字段名",
        dataIndex: "apiFieldName",
        key: "apiFieldName",
        slots: { customRender: "apiFieldName" },
      },
      {
        title: "中心库字段名",
        dataIndex: "cenFieldName",
        key: "cenFieldName",
        slots: { customRender: "cenFieldName" },
      },
      {
        title: "临时库字段名",
        dataIndex: "tmpFieldName",
        key: "tmpFieldName",
        slots: { customRender: "tmpFieldName" },
      },
      {
        title: "同步类型",
        dataIndex: "opType",
        key: "opType",
        slots: { customRender: "opType" },
      },
      {
        title: "缺省值",
        dataIndex: "defaultVal",
        key: "defaultVal",
        slots: { customRender: "defaultVal" },
      },
      {
        title: "操作",
        dataIndex: "operation",
        slots: { customRender: "operation" },
      },
    ];
    const columns = [
      {
        title: "说明",
        dataIndex: "name",
        key: "name",
        slots: {
          filterDropdown: "filterDropdown",
          filterIcon: "filterIcon",
          customRender: "customRender",
        },
        onFilter: (value, record) =>
          record.name.toString().toLowerCase().includes(value.toLowerCase()),
        onFilterDropdownVisibleChange: (visible) => {
          if (visible) {
            setTimeout(() => {
              console.log(searchInput.value);
              searchInput.value.focus();
            }, 0);
          }
        },
      },
      {
        title: "中心库表名",
        dataIndex: "cenTableName",
        key: "cenTableName",
      },
      {
        title: "临时库表名",
        dataIndex: "tmpTableName",
        key: "tmpTableName",
      },
      {
        title: "接口地址",
        dataIndex: "apiUrl",
        key: "apiUrl",
      },
      {
        title: "状态",
        dataIndex: "status",
        key: "status",
        slots: { customRender: "status" },
      },
      {
        title: "分页大小",
        dataIndex: "pageSize",
        key: "pageSize",
      },
      {
        title: "操作",
        key: "action",
        slots: { customRender: "action" },
      },
    ];

    onBeforeMount(async () => {
      loadData();
    });

    const loadData = () => {
      ApiMachList(1, 10)
        .then((response) => {
          let object = response.data;
          state.dataList = object.records;
          console.log(state);
        })
        .catch((error) => {
          console.log(error);
        });
    };

    const onDelete = async (obj) => {
      let result = await ApiMachDelete(obj.syncTableId);
      if (result.status == 1) {
        message.success("删除成功！");
        loadData();
      }
    };

    const onEdit = async (obj) => {
      state.spinning = true;
      let result = await ApiMachGetDetail(obj.syncTableId);
      let object = result.data;
      state.formState = object;
      console.log(state.formState);

      result = await ApiMachGetSourceTable();
      state.optionsTempTable = [];
      result.data.forEach((element) => {
        state.optionsTempTable.push({
          value: element,
          label: element,
        });
      });
      result = await ApiMachGetTargetTable();
      state.optionsCenterTable = [];
      result.data.forEach((element) => {
        state.optionsCenterTable.push({
          value: element,
          label: element,
        });
      });

      state.spinning = false;

      console.info(state);
      state.visible = true;
      state.modelTitle = "修改信息";
    };

    const onUpdateStatus = (obj, status) => {
      ApiMachUpdateStatus(obj.syncTableId,status)
        .then((response) => {
          let object = response.data;
          console.log(object);
          loadData();
        })
        .catch((error) => {
          message.error(error.error_message_zh);
          console.log(error);
        });
    };

    const handleOk = () => {
      console.log(state.formState);
      ApiMachSaveSyncConfig(state.formState)
        .then((response) => {
          debugger;
          let object = response.data;
          console.log(object);
          state.visible = false;

          loadData();
        })
        .catch((error) => {
          message.error(error.error_message_zh);
          console.log(error);
        });
    };

    const edit = async (row) => {
      row.opType = row.opType + "";
      editableData[row.apiFieldName] = cloneDeep(row);
      let result = await ApiMachGetTargetField(state.formState.cenTableName);
      state.optionsCenter = [];
      result.data.forEach((element) => {
        state.optionsCenter.push({
          value: element,
          label: element,
        });
      });

      result = await ApiMachGetSourceField(state.formState.tmpTableName);
      state.optionsTemp = [];
      result.data.forEach((element) => {
        state.optionsTemp.push({
          value: element,
          label: element,
        });
      });
    };
    const save = (key) => {
      state.formState.fields.forEach((item) => {
        if (key === item.apiFieldName) {
          Object.assign(item, editableData[key]);
        }
      });

      delete editableData[key];
    };
    const cancel = (key) => {
      delete editableData[key];
    };
    const remove = (key) => {
      debugger;
      let tmpList = [];
      state.formState.fields.forEach((element) => {
        if (element.apiFieldName != key) tmpList.push(element);
      });
      state.formState.fields = tmpList;
      delete editableData[key];
    };

    const addField = () => {
      state.formState.fields.push({});
    };
    const addTable = async () => {
      state.formState = {
        fields: [],
      };

      let result = await ApiMachGetSourceTable();
      state.optionsTempTable = [];
      result.data.forEach((element) => {
        state.optionsTempTable.push({
          value: element,
          label: element,
        });
      });
      result = await ApiMachGetTargetTable();
      state.optionsCenterTable = [];
      result.data.forEach((element) => {
        state.optionsCenterTable.push({
          value: element,
          label: element,
        });
      });

      state.visible = true;
      state.modelTitle = "添加对码表";
    };
    return {
      ...toRefs(state),
      columns,
      columnsFormState,
      searchText: "",
      searchedColumn: "",
      searchInput,
      onDelete,
      onEdit,
      handleOk,
      editableData,
      edit,
      save,
      cancel,
      addField,
      addTable,
      onUpdateStatus,
      remove,
    };
  },
};
</script>
<style scoped>
.highlight {
  background-color: rgb(255, 192, 105);
  padding: 0px;
}
.paddLeft {
  padding-left: 12px;
}
</style>